import {
  getInputSourceConfigs,
  updateInputSourceConfig,
} from '@/services/InputSourceSerivce';
import { DisableType, InputSourceConfig } from '@/types';
import { useModel } from '@umijs/max';
import { useEffect, useMemo, useState } from 'react';
import { useRequest } from 'umi';
import { isNotBlank } from 'web-plugin-utils';

// @ts-ignore
export default () => {
  const [inputSourceConfigs, setInputSourceConfigs] = useState<
    InputSourceConfig[]
  >([]);

  // @ts-ignore
  const { initialState } = useModel('@@initialState');

  // @ts-ignore
  const { run: reloadInputSourceConfigs } = useRequest<any>(
    () => getInputSourceConfigs(`http://${initialState?.videoMatrixIp}`),
    {
      manual: true,
      onSuccess(data) {
        setInputSourceConfigs(data);
      },
    },
  );

  useEffect(() => {
    if (initialState) {
      if (isNotBlank(initialState!.videoMatrixIp!)) {
        reloadInputSourceConfigs();
      }
    }
  }, [initialState?.videoMatrixIp]);

  //启用的视频输入设备
  const enabledInputSourceConfigs = useMemo(() => {
    return (inputSourceConfigs || []).filter(
      //disabled手动禁用 enabled服务端是否启用
      (c: InputSourceConfig) => c.disabled === DisableType.Off && c.enabled,
    );
  }, [inputSourceConfigs]);

  const [putInSourceName, setPutInSourceName] = useState<string | undefined>();

  //更新视频输入配置
  const updateInputSourceConfigs = async (
    inputSourceConfigs: InputSourceConfig[],
  ) => {
    await updateInputSourceConfig(
      `http://${initialState!.videoMatrixIp!}`,
      inputSourceConfigs,
    );
    await reloadInputSourceConfigs();
  };

  //更新视频输入配置
  const proxyUpdateInputSourceConfig = async (
    inputSourceConfig: InputSourceConfig,
  ) => {
    const configIndex = inputSourceConfigs.findIndex(
      (c: InputSourceConfig) => c.workerName === inputSourceConfig.workerName,
    );
    if (configIndex !== -1) {
      inputSourceConfigs[configIndex] = inputSourceConfig;
      await updateInputSourceConfigs(inputSourceConfigs);
    }
  };

  return {
    putInSourceName,
    setPutInSourceName,
    inputSourceConfigs,
    enabledInputSourceConfigs,
    updateInputSourceConfig: proxyUpdateInputSourceConfig,
    updateInputSourceConfigs,
    reloadInputSourceConfigs,
  };
};
